<template>
 <div>
     <el-container>
         <el-header height="76px">
             <h2>城市信息管理</h2>
             <!-- 面包屑导航区域 -->
             <el-breadcrumb separator="/">
                 <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
                 <el-breadcrumb-item>城市信息管理</el-breadcrumb-item>
             </el-breadcrumb>
         </el-header>
         <el-main>
             <div class="main-title">
                 <h3>城市列表</h3>
                 <button
                         class="new-add"
                         @click="addFormVisible = true"
                 ></button>
             </div>
             <!-- 搜索 -->
             <el-row :gutter="20">
                 <el-col :span="23" class="search-col">
                     <keep-alive>
                         <el-input
                                 placeholder="查询（输入要查询的城市或省份）"
                                 size="small"
                                 v-model="keyword"
                                 @input="handelQuery"
                         >
                         </el-input>
                     </keep-alive>
                 </el-col>
             </el-row>
             <!-- 表格 -->
             <el-table
                     stripe
                     :default-sort="{ prop: 'cityNumber', order: 'descending' }"
                     :data="cityData"
                     highlight-current-row
             >
                 <el-table-column prop="cityNumber" label="城市编号" sortable />
                 <el-table-column prop="province" label="所属省" />
                 <el-table-column prop="city" label="城市名称" />
                 <el-table-column prop="cityOperation" label="操作" >
                     <!-- 通过slot-scope拿到对应行的数据 -->
                     <template slot-scope="scope">
                         <button
                                 class="table-btn-delete"
                                 @click="deleteCity(scope.row.cityId,scope.row)"
                         ></button>
                     </template>
                 </el-table-column>
             </el-table>
             <!-- 分页 -->
             <div class="pagination">
                 <el-pagination
                         :current-page.sync="currentPage"
                         :page-size.sync="pageSize"
                         :layout="'total,prev,pager,next,jumper'"
                         :total="total"
                         @current-change="handleCurrentChange"
                 />
             </div>
         </el-main>
         <el-dialog
                 title="新增城市"
                 :visible.sync="addFormVisible"
                 :modal-append-to-body="false"
                 @close="handleAddClose"
         >
             <el-form :model="addForm" hide-required-asterisk ref="addForm">
                 <el-form-item
                         label="城市名称"
                         :label-width="formLabelWidth"
                         prop="cityNumber"
                         :rules="rules.requiredRules"
                 >
                     <el-cascader
                             size="large"
                             :options="options"
                             v-model="addForm.cityNumber"
                     >
                     </el-cascader>
                 </el-form-item>
             </el-form>
             <div slot="footer" class="dialog-footer">
                 <el-button @click="addFormVisible = false">取 消</el-button>
                 <el-button type="primary" @click="AddCity('addForm')"
                 >确 定</el-button
                 >
             </div>
         </el-dialog>
     </el-container>
 </div>
</template>
<script>
import rules from "../../utils/validator";
import {provinceAndCityData} from "element-china-area-data/dist/app";
import service from "@/utils/request";
export default {
    name: "cityIndex",
    data(){
        return {
            currentPage: 1,
            pageSize: 5, // 每页的数据条数
            total:0,
            cityData:[],
            keyword: "",
            addFormVisible: false, // 控制新增城市页面的显示
            addForm: {
                cityNumber: [],
            },
            formLabelWidth: "110px", //表单 label 的宽度
            rules, // 封装好的表单验证
            options: provinceAndCityData, //element-china-area-data组件
        };
    },
    mounted() {
        this.getCityInfo(); // 首次渲染
    },
    methods:{
        //添加城市
        AddCity(formName){
            this.$refs[formName].validate((valid) => {
                //检查表单
                if (valid) {
                    service.post("/city/addCity",
                        {
                            cityNumber: this.addForm.cityNumber[1]
                        })
                        .then(res => {
                            if (res.code === 200) {
                                this.$message({
                                    message: res.message,
                                    type: "success"
                                })
                                this.addFormVisible = false
                                //刷新页面，同步数据库页码，并跳到最后一页
                                this.getCityInfo().then(()=>{
                                    this.currentPage=Math.ceil(this.total / this.pageSize);//计算总页数，并赋值该当前页
                                    this.getCityInfo()
                                })

                            } else {
                                this.$message({
                                    message: res.message,
                                    type: "error"
                                })
                            }
                        })
                }else {
                    this.$message.error('请按照要求输入');
                    return false;
                }
            });
        },


        //通过Id删除城市
        deleteCity(id,cityRef){
            this.$confirm(
                `确定要删除“${cityRef.city}”的相关信息吗？该操作会同时删除对应的城市政策`,
                "提示",
                {
                    confirmButtonText: "确定",
                    cancelButtonText: "取消",
                    type: "warning",
                })
                .then(() => {
                    service.get("/city/deleteCity/"+id).then(res=>{
                        if(res.code===200){
                            this.$message({
                                message: res.message,
                                type:"success"
                            })
                            //刷新页面
                            this.currentPage=1
                            this.getCityInfo()
                        }else {
                            this.$message({
                                message: res.message,
                                type:"error"
                            })
                        }}
                    )})
                .catch(() => {
                    this.$message({
                        type: "info",
                        message: "已取消删除",
                    });
                })
        },

        //获取关键字并准备模糊查询
        handelQuery(){
            this.currentPage=1
            this.doSearch()
        },
        //模糊查询城市
        doSearch(){
            //调用接口
            service.get("/city/getAllCity",{
                params:{
                    key:this.keyword,
                    currentPage:this.currentPage,
                    pageSize:this.pageSize
                }
            }).then(res=>{
                if(res.code===200){
                    this.cityData=res.data.list
                    this.total=res.data.total
                }else {
                    //没有更多数据，更新表组件数据
                    this.cityData=[]
                    this.total=0
                    this.currentPage=1
                }
            })
        },
        //获取所有的城市
        getCityInfo(){
          return service.get("/city/getAllCity",{
                params:{
                    currentPage:this.currentPage,
                    pageSize:this.pageSize
                }
            }).then((res)=>{
                if(res.code===200){
                    this.cityData=res.data.list
                    this.total = res.data.total
                }else {
                    this.cityData=[]
                    this.total=0
                    this.currentPage=1
                }
            })
        },
        //点击某一行修改按钮时，开启弹窗，给表单赋值
        handleModifyOpen(oldData){
            this.modifyFormVisible=true;
            this.modifyForm=oldData;
        },
        // 每次关闭表单的时候重置表单
        handleAddClose() {
            this.addForm = {};
            this.$refs.addForm.resetFields();
        },
        //分页器页码改变时触发
        handleCurrentChange(){
            if (this.keyword.length) {
                this.doSearch();
            } else {
                this.getCityInfo();
            }
        },
    }
}
</script>
<style scoped lang="less">
@import "../../style/infoManage.less";
</style>